package partner_middleware

import (
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/gin-gonic/gin"
	"runtime/debug"
)

func Recover(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			// 打印错误堆栈信息
			app.Log().Error("异常-" + errorToString(r))
			debug.PrintStack()
			app.NewResponse(c).ErrorReturn(app.ServerError)
			// 终止后续接口调用，不加的话recover到异常后，还会继续执行接口里后续代码
			c.Abort()
		}
	}()

	c.Next()
}

func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}
